package com.truyen.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.ConnectController;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.FeedOperations;
import org.springframework.social.facebook.api.Post;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.view.RedirectView;

import com.truyen.social.SocialContext;



@Controller
@RequestMapping("/fb")
public class FacebookController{
	
	private static final Logger logger = LoggerFactory.getLogger(FacebookController.class);

	  private final SocialContext socialContext;

	  @Autowired
	  public FacebookController(SocialContext socialContext) {
	    this.socialContext = socialContext;
	  }

	  
	protected RedirectView connectionStatusRedirect(String providerId) {
		return new RedirectView(providerId +".htm", true);
	}
	  
	  @RequestMapping(value = "posts.htm", method = RequestMethod.GET)
	  public String showPostsForUser(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
	    String nextView;
	    if (socialContext.isSignedIn(request, response)) {
	      List<Post> posts = retrievePosts();
	      model.addAttribute("posts", posts);
	      nextView = "post";
	    } else {
	      nextView = "/login/login";
	    }
	    return nextView;
	  }

	  private List<Post> retrievePosts() {
	    Facebook facebook = socialContext.getFacebook();
	    FeedOperations feedOps = facebook.feedOperations();
	    List<Post> posts = feedOps.getHomeFeed();
	    logger.info("Retrieved " + posts.size() + " posts from the Facebook authenticated user");
	    return posts;
	  }
}